/**
 * Created by lee_mxue on 17/2/9.
 */
import React from "react";
import ReactDOM from "react-dom";
import AJAX from "../../lib/ajax";
import Rules from "../../lib/rules";
import Toast from "../MyPackage/components/Toast";
import Tools from '../../lib/tools'
import { addErrorListener } from "../../lib/handleError"
import weixinShare from "../../lib/weixinShare";

require('../../lib/rem');
require('./SendingPackageEditReceiverAddress.less');
// require('../SendingPackageChooseSite/SendingPackageChooseSite.less');
require('../../styles/common.less');
require('../../styles/resetWeui.less');
require('../../styles/lux.less');
//判断寄件类型（1: 服务站点寄件    2: 柜体寄件）
const sendType = Tools.getParams().send_type;

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isReady: false,     //是否加载页面
            textAreaIsOpen: false,
            actionSheetIsOpen: false,
            tagTextAreaIsOpen: false,   //地址标签自定义输入
            addr_id: 0,   //地址id
            tagList: ['朋友', '客户', '同学'],   //地址标签
            receiverName: "",   //收件人姓名
            receiverPhone: "",  //收件人电话
            receiverAddress: "",    //收件人详细地址
            receiveProvinceCode: "",    // 省份编码
            receiverCityCode: "",    // 城市编码
            receiverCountyCode: "",    // 区县编码
            receiverTag: "",    // 标签名
            areaData: [],   //区域列表数据
            selectFirstArea: '请选择', //已选省份
            selectSecondArea: '',   //已选市
            selectThirdArea: '',    //已选县
        };
        this.switchTextarea = this.switchTextarea.bind(this)    //控制自动识别输入框显示
        this.switchSiteList = this.switchSiteList.bind(this)    //打开地区选择－－－获取一级区域列表
        this.getReceiverInfo = this.getReceiverInfo.bind(this)  //获取输入框内容
        this.handleClearInfo = this.handleClearInfo.bind(this)  //清楚输入框内容
        this.getReceiverTag = this.getReceiverTag.bind(this)  //获取收件人标签
        this.getAreaData = this.getAreaData.bind(this)  //获取区域列表信息
        this.switchInputTag = this.switchInputTag.bind(this)  //输入自定义标签
        this.handleIdentify = this.handleIdentify.bind(this)  //自动识别
        this.handleDelete = this.handleDelete.bind(this)  //删除
        this.handleSubmit = this.handleSubmit.bind(this)  //提交
    }

    componentWillMount() {
        addErrorListener()()
        weixinShare.hideAll();
        // 获取收件人详情
        var receiverData = JSON.parse(localStorage.getItem('receiverData_x'))
        this.setState({
            receiverName: receiverData.realname,   //收件人姓名
            receiverPhone: receiverData.phone,  //收件人电话
            receiverAddress: receiverData.address,    //收件人详细地址
            receiveProvinceCode: receiverData.province_code,    // 省份编码
            receiverCityCode: receiverData.city_code,    // 城市编码
            receiverCountyCode: receiverData.county_code,    // 区县编码
            receiverTag: receiverData.tag,    // 标签名

            addr_id: receiverData.id,   //地址id
            selectFirstArea: receiverData.province, //已选省份
            selectSecondArea: receiverData.city,   //已选市
            selectThirdArea: receiverData.county,    //已选县
        })
    }

    componentDidMount() {
        AJAX.appendBaiduAnalysis()
        this.setState({
            isReady: true,     //是否加载页面
        })
    }

    //控制自动识别输入框显示
    switchTextarea() {
        this.setState({
            textAreaIsOpen: !this.state.textAreaIsOpen
        })
    }

    //打开地区选择－－－获取一级区域列表
    switchSiteList(isOpen) {
        // console.log("isopen: ", isOpen)
        if (isOpen == true) {
            //清空已选
            this.setState({
                selectFirstArea: '请选择',
                selectSecondArea: '',
                selectThirdArea: '',
                receiveProvinceCode: "",    // 省份编码
                receiverCityCode: "",    // 城市编码
                receiverCountyCode: "",    // 区县编码
            });
            AJAX.request("area_search", {
                parent_code: '001'
            }, (data) => {
                if (data.code == 0) {
                    // console.log("data: ", data)
                    let myAreaData = data.body;
                    this.setState({
                        areaData: myAreaData,
                        actionSheetIsOpen: isOpen
                    })

                }

            })
        } else {
            this.setState({
                actionSheetIsOpen: isOpen
            })
        }
    }

    //获取区域列表信息（二 三 级）
    getAreaData(area_code, scope, area_name) {
        switch (scope)  //判断范围级别
        {
            case 1:
                this.setState({
                    selectFirstArea: area_name,
                    receiveProvinceCode: area_code,    // 省份编码
                })
                break;
            case 2:
                this.setState({
                    selectSecondArea: area_name,
                    receiverCityCode: area_code,    // 城市编码
                })
                break;
            case 3:
                this.setState({
                    selectThirdArea: area_name,
                    receiverCountyCode: area_code,    // 区县编码
                })
                this.switchSiteList(false)
                break;

        }

        AJAX.request("area_search", {
            parent_code: area_code
        }, (data) => {
            if (data.code == 0) {
                // console.log("data: ", data)
                let myAreaData = data.body;
                this.setState({
                    areaData: myAreaData,
                })
            }

        })
    }

    //获取输入框内容
    getReceiverInfo(type, e) {
        var value = e.target.value
        this.setState({
            [type]: value
        })
        //编辑地址标签
        if (type == 'receiverTag') {
            var tagList = this.state.tagList;
            tagList.push(value)
            this.setState({
                tagList: tagList
            })
        }
    }

    //手动清楚输入框内容
    handleClearInfo(type) {
        this.setState({
            [type]: ""
        })
    }

    //获取收件人标签
    getReceiverTag(tag) {
        this.setState({
            receiverTag: tag
        })
    }

    //自定义标签输入框显示
    switchInputTag() {
        this.setState({
            tagTextAreaIsOpen: !this.state.tagTextAreaIsOpen
        })
    }

    //自动识别
    handleIdentify() {
        //清空已选地址
        this.setState({
            selectFirstArea: '请选择',
            selectSecondArea: '',
            selectThirdArea: '',
            receiveProvinceCode: "",    // 省份编码
            receiverCityCode: "",    // 城市编码
            receiverCountyCode: "",    // 区县编码
        });
        var receiverName = "";  //收件人姓名
        var receiverPhone = "";  //收件人电话
        var receiverAddress = "";    //收件人详细地址

        var value = this.refs.textarea.value;
        var val_list_all = [];  //全部内容
        var val_list_real = [];  //非空内容
        val_list_all = value.split(/[\n\s]/g);   //用换行 和 空格分割
        // console.log("val_list: ", val_list_all)
        //去除空字符串
        val_list_all.map((val, key) => {
            if (val.length > 0) {
                var item = {
                    val: val,
                    size: val.length,
                    key: key,
                }
                val_list_real.push(item);
            }
        });

        //设置字符最短长度
        var min_size = 1;
        val_list_real.map((item, k) => {
        //    识别电话---是数字
            if(!isNaN(parseInt(item.val))){
                receiverPhone = item.val
                //从数组中去除
                val_list_real.splice(k, 1)
            }else{
                //识别姓名和地址
                if(k > 0 && item.size > val_list_real[k-1].size){
                    receiverName = val_list_real[k-1].val;
                    receiverAddress = item.val;
                }else if(item.size > val_list_real[k+1].size){
                    receiverName = val_list_real[k+1].val;
                    receiverAddress = item.val;
                }
            }
        })

        this.setState({
            receiverName: receiverName,  //收件人姓名
            receiverPhone: receiverPhone,  //收件人电话
            receiverAddress: receiverAddress,
        })
    }

    //删除
    handleDelete() {
        AJAX.request("address_delete", {
            addr_id: this.state.addr_id,    // 地址id
        }, (data) => {
            if (data.code == 0) {
                //判断寄件类型（1: 服务站点寄件    2: 柜体寄件）
                window.location.href = './SendingPackageReceiverAddress?send_type='+sendType
            }

        })
    }

    //提交
    handleSubmit() {
        //    验证姓名
        if (this.state.receiverName.length == 0) {
            Toast.warn({
                content: '请输入姓名'
            });
        } else if (!Rules.len(this.state.receiverName, 2, 40)) {
            Toast.warn({
                content: '姓名格式错误'
            });
            //    验证联系方式
        } else if (this.state.receiverPhone.length == 0) {
            Toast.warn({
                content: '请输入联系方式'
            });
        } else if (!Rules.phone(this.state.receiverPhone) && !Rules.officePhone(this.state.receiverPhone)) {
            Toast.warn({
                content: '联系方式格式错误'
            });
            //    验证区县编码
        } else if (this.state.receiverCountyCode == 0) {
            Toast.warn({
                content: '请选择城市区域'
            });
            //    验证地址
        } else if (this.state.receiverAddress.length == 0) {
            Toast.warn({
                content: '请输入详细地址'
            });
        } else if (!Rules.len(this.state.receiverAddress, 1, 100)) {
            Toast.warn({
                content: '详细地址格式错误'
            });
            //    验证地址标签
        } else if (this.state.receiverTag == 0) {
            Toast.warn({
                content: '请选择地址标签'
            });
        } else {
            AJAX.request("address_update", {
                addr_id: this.state.addr_id,    // 地址id
                realname: this.state.receiverName,    // 姓名
                phone: this.state.receiverPhone,    // 电话
                province_code: this.state.receiveProvinceCode,    // 省份编码
                city_code: this.state.receiverCityCode,    // 城市编码
                county_code: this.state.receiverCountyCode,    // 区县编码
                address: this.state.receiverAddress,    // 详细地址
                tag: this.state.receiverTag,    // 标签名
            }, (data) => {
                if (data.code == 0) {
                    //判断寄件类型（1: 服务站点寄件    2: 柜体寄件）
                    window.location.href = './SendingPackageReceiverAddress?send_type='+sendType
                }

            })
        }

    }

    render() {
        var actionSheetClassName = this.state.actionSheetIsOpen ? " weui-actionsheet weui-actionsheet_toggle" : "weui-actionsheet";
        var maskClassName = this.state.actionSheetIsOpen ? " weui-mask" : "weui-mask none";
        var goodsInputClassName = this.state.tagTextAreaIsOpen ? "weui-cell weui-cell_primary" : "none"; //地址标签－－－其他

        return (
            this.state.isReady &&
            <div>
                <div className="weui-cells">
                    <div className="weui-cell">
                        <div className="weui-cell__hd"><label className="weui-label">姓名</label></div>
                        <div className="flex weui-cell__bd">
                            <input className="weui-input" value={this.state.receiverName}
                                   onChange={this.getReceiverInfo.bind(this, "receiverName")} required="required"
                                   autoComplete="autoComplete"
                                   placeholder="请填写真实姓名"/>
                            <i onClick={this.handleClearInfo.bind(this, "receiverName")}
                               className="iconfont iconG icon-cuowu"></i>
                        </div>
                    </div>
                    <div className="weui-cell ">
                        <div className="weui-cell__hd">
                            <label className="weui-label">联系方式</label>
                        </div>
                        <div className="flex weui-cell__bd">
                            <input className="weui-input" value={this.state.receiverPhone}
                                   onChange={this.getReceiverInfo.bind(this, "receiverPhone")} required="required"
                                   autoComplete="autoComplete" type="tel"
                                   placeholder="请填写联系方式"/>
                            <i onClick={this.handleClearInfo.bind(this, "receiverPhone")}
                               className="iconfont iconG icon-cuowu"></i>
                        </div>
                    </div>
                    <div className="weui-cell" onClick={this.switchSiteList.bind(this, true)}>
                        <div className="weui-cell__hd">
                            <label className="weui-label">选择城市</label>
                        </div>
                        <div className="weui-cell__bd chooseCity textG">
                            {this.state.selectFirstArea} {this.state.selectSecondArea} {this.state.selectThirdArea}
                        </div>

                    </div>
                    <div className="weui-cell">
                        <div className="weui-cell__hd"><label className="weui-label">详细地址</label></div>
                        <div className="flex weui-cell__bd">
                            <textarea className="weui-textarea" value={this.state.receiverAddress}
                                      onChange={this.getReceiverInfo.bind(this, "receiverAddress")}
                                      autoComplete="autoComplete" placeholder="请详细到门牌号"/>
                            <i onClick={this.handleClearInfo.bind(this, "receiverAddress")}
                               className="iconfont iconG icon-cuowu"></i>
                        </div>
                    </div>
                </div>

                <div className="weui-cells__title">
                    <span onClick={this.switchTextarea}>地址智能识别板</span>
                </div>
                {this.state.textAreaIsOpen && <div className="weui-cells weui-cells_form">
                    <div className="weui-cell auto_textarea">
                        <div className="weui-cell__bd">
                            <textarea className="weui-textarea fontSize12px"
                                      ref="textarea"
                                      placeholder="长按可将地址信息粘贴于此进行编辑，信息使用空格或者换行符间隔，不区分先后顺序，编辑完成后点击『智能识别』按钮自动识别。信息格式如：北京市北京市朝阳区酒仙桥街道甲4号宏源大厦22层2201室    张三   18888888888"
                                      rows="3"></textarea>
                            <div className="weui-textarea-counter">
                                <span onClick={this.handleIdentify}>
                                    智能识别
                                </span>
                            </div>
                        </div>
                    </div>
                </div>}

                <div className="weui-cells check_list">
                    <div className="weui-cell weui-cell_primary">
                        <div className="weui-cell__hd"><label className="weui-label">地址标签</label></div>
                        <div className=" flex weui-cell__bd" style={{overflow: 'scroll'}}>
                            <p>
                                {this.state.tagList.map(item => {
                                    return (
                                        <span className={` ${this.state.receiverTag == item ? '' + 'textBlue' : ''}`}
                                              onClick={this.getReceiverTag.bind(this, item)}>{item}</span>
                                    )
                                })}
                            </p>
                        </div>
                    </div>

                </div>

                <div className="weui-btn-area submit_btn">
                    <a className="weui-btn weui-btn_primary" onClick={this.handleSubmit} href="javascript:;"
                       id="showTooltips">确定</a>
                    <a className="weui-btn weui-btn_primary red" onClick={this.handleDelete} href="javascript:;"
                       id="showTooltips">删除</a>


                </div>

                {/*选择城市*/}
                <div>
                    <div className={maskClassName} id="iosMask" onClick={this.switchSiteList.bind(this, false)}></div>
                    <div className={actionSheetClassName} id="iosActionsheet">
                        <div className="weui-cells">
                            <div className="weui-cell">
                                <div className="weui-cell__bd">
                                    <p></p>
                                </div>
                                <div className="weui-cell__ft" onClick={this.switchSiteList.bind(this, false)}>
                                    <i className="iconfont iconG icon-cha"></i>
                                </div>
                            </div>
                            <div className="weui-cell">
                                <div className="weui-cell__bd">
                                    <p>
                                        <span>{this.state.selectFirstArea}  </span>
                                        <span>{this.state.selectSecondArea}  </span>
                                        <span >{this.state.selectThirdArea}  </span>
                                    </p>
                                </div>
                                <div className="weui-cell__ft"></div>
                            </div>
                        </div>
                        <div className="weui-actionsheet__menu">
                            {
                                this.state.areaData.map(data => {
                                    return (
                                        <div className="weui-actionsheet__cell">
                                            <p data-area_code={data.area_code}
                                               onClick={this.getAreaData.bind(this, data.area_code, data.scope, data.area_name, data.area_code)}>{data.area_name}</p>
                                        </div>
                                    )

                                })
                            }

                        </div>
                    </div>
                </div>
            </div>

        )
    }
}
ReactDOM.render(<App />, document.getElementById('app'));
if (module.hot) {
    module.hot.accept();
}